package com.security.service.impl;

import com.security.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-06 9:18
 * @description：
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        boolean hasPermission = false;

        // 获取用户信息
        Object principal = authentication.getPrincipal();

        //
        if(principal instanceof UserDetails){
            // 获取用户名
            String username = ((UserDetails) principal).getUsername();
            log.info("当前校验权限的用户名：{}", username);
            // 模拟从数据库中查出的当前用户所拥有的权限的url
            HashSet<String> urls = new HashSet<>();

            urls.add("/user/info");

            for (String url : urls) {
                if(antPathMatcher.match(url, request.getRequestURI())){
                    hasPermission = true;
                    break;
                }
            }
        }
        log.info("{} :是否通过权限校验：{}", request.getRequestURI(), hasPermission);
        return hasPermission;
    }
}
